const app = getApp();
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const wxParser = require('../../wxParser/index');
var loginStatus = wx.getStorageSync("loginStatus");
const {
  $Toast
} = require('../../components/base/base');

Page({

  data: {
    navBg: app.globalData.navBg,
    navColor: app.globalData.navColor,
    windowHeight: app.globalData.windowHeight - app.globalData.navHeight,
    windowH: app.globalData.windowHeight,
    navTop: app.globalData.navHeight,
    navHeight: app.globalData.navHeight,
    searchWidth: app.globalData.menuButtonRight,
    cHeight: '0',
    dataitem: [{
      id: 1,
      name: '商品'
    }, {
      id: 2,
      name: '规格'
    }, {
      id: 3,
      name: '详情'
    }],
    activeId: 0,
    activeScrollTop: '0',
    toView: 'index0',
    scrollTop: null,
    goodsimg: [],
    goodsimgSrc: [],
    swiperCurrent: 0,
    imgHeight: '',
    imgItem: [],
    itemdetail: [],
    num: 1,
    setdialoag: false,
    swiperset: 0,
    setitemdialoag: false,
    setmealstatus: false,
    minusStatus: true,
    goTop: true,
    navCont: 0, //购物车商品数量
    icon_collect: true
  },

  navBack: function(e) {
    try {
      wx.navigateBack({
        delta: 1,
        fail: function(e) {

        }
      })
    } catch (e) {
      console.log(e)
    }
  },

  clickLeft: function(e) {
    let i = e.currentTarget.id
    this.setData({
      activeId: i,
      toView: 'index' + i
    })
  },

  scrollLeft: function(e) {
    this.setData({
      activeScrollTop: e.detail.scrollTop
    })
  },

  scrollRight: function(e) {

    let {
      itemArr,
      activeId,
      activeScrollTop,
      cHeight
    } = this.data;

    itemArr.every((c, ci) => {
      if (e.detail.scrollTop < c) return this.setData({
        activeId: ci
      }); //false 停止遍历
      else return true
    })

    let activeCurHeight = activeId * 40;

    this.setData({
      activeScrollTop: activeCurHeight - cHeight / 2,
      scrollTop: e.detail.scrollTop
    })

    var listIndex = (e.detail.scrollTop + this.data.screenHeight) / (this.data.screenWidth * 0.4)
    if (e.detail.scrollTop > app.globalData.navHeight + 40) {
      this.setData({
        goTop: false
      });
      this.setData({
        listIndex: listIndex
      })
    } else {
      this.setData({
        goTop: true
      });
    }

  },

  //轮播图高度自适应
  imgH: function(e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height;　　　　　　　　　　　 //图片高度
    var imgw = e.detail.width;
    //等比设置swiper的高度 (即屏宽/swiper高度)=图片宽/图片高==》swiper高度=屏宽*图片高度/图片宽度
    var swiperH = winWid * imgh / imgw + "px"
    this.setData({
      imgHeight: swiperH　　　　　　　　 //设置高度
    })
  },

  //轮播图的切换事件
  swiperChange: function(e) {
    if ("touch" === e.detail.source) {
      this.setData({
        swiperCurrent: e.detail.current
      })
    }

  },

  //预览图片
  previewImg: function(e) {
    var index = e.currentTarget.dataset.index;
    var imgArr = this.data.itemdetail;
    wx.previewImage({
      current: imgArr[index],
      urls: imgArr,
      success: function(res) {

      },
      fail: function(res) {},
      complete: function(res) {},
    })

  },

  /* 点击减号 */
  bindMinus: function() {
    var num = this.data.num;
    if (num > 1) {
      num--;
    }
    var minusStatus = num <= 1 ? true : false;
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },

  /* 点击加号 */
  bindPlus: function() {
    var num = this.data.num;
    num++;
    var minusStatus = num <= 1 ? true : false;
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },

  /* 输入框事件 */
  bindManual: function(e) {
    var num = parseInt(e.detail.value.replace(/\s+/g, ''));
    this.setData({
      num: num
    });
  },

  manualValue: function(e) {
    var num = parseInt(e.detail.value.replace(/\s+/g, ''));
    this.setData({
      num: num
    })
  },

  slideimg: function() {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var slideimgw = (winWid - 50) / 3
    this.setData({
      slideimgW: slideimgw.toFixed(3),
      slideimgH: slideimgw.toFixed(3)
    })
  },

  swiperset: function(e) {
    if ("touch" === e.detail.source) {
      this.setData({
        swiperset: e.detail.current
      })
    }
  },

  imgHswiperset: function(e) {
    this.setData({
      setdialoag: false
    })
  },

  // 套餐内容预览
  setmealTap: function(e) {
    var that = this;
    var index = e.target.dataset.index;
    var src = e.target.dataset.src;
    var id = e.target.dataset.id;
    var imgsrcs = that.data.setlen;
    that.setData({
      setdialoag: true,
      imgsrcs: imgsrcs,
      imgsrcslen: imgsrcs.length,
      swiperset: index
    })

  },

  // 套餐内容
  setmeal: function(res) {
    var that = this;
    wx.request({
      url: util.api + 'detail/setmeal.json',
      method: 'GET',
      header: {
        'Content-type': 'application/json'
      },
      success: function(res) {
        that.setData({
          setmeal: res.data.result
        })
        var setlen = [];
        for (var i = 0; i < res.data.result.length; i++) {
          setlen.push(res.data.result[i])
        }
        that.setData({
          setlen: setlen
        })

      },
      fail: function(res) {

      }
    })
  },

  // 套餐内容详细
  toItemset: function(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    that.setData({
      setitemdialoag: true
    })
    var setmealitem = [];
    var setmealPic = []
    for (var i = 0; i < that.data.setlen.length; i++) {
      if (that.data.setlen[i].id == id) {
        setmealitem.push(that.data.setlen[i]);
        setmealPic.push(that.data.setlen[i].info)
      }
    }

    var postdata = setmealPic.join("-");
    if (JSON.stringify(setmealPic) == '[""]' || JSON.stringify(setmealPic) == '[null]' || JSON.stringify(setmealPic) == '[undefined]') {
      wxParser.parse({
        bind: 'richText', //绑定的数据名称
        html: '暂无套餐内容', //HTML 内容
        target: that, //绑定数据的模块对象
        enablePreviewImage: true, //是否启用富文本内的图片预览功能
        tapLink: (url) => { //点击超链接时的回调函数
        }
      });
    } else {
      wxParser.parse({
        bind: 'richText', //绑定的数据名称
        html: postdata, //HTML 内容
        target: that, //绑定数据的模块对象
        enablePreviewImage: true, //是否启用富文本内的图片预览功能
        tapLink: (url) => { //点击超链接时的回调函数
        }
      });
    }

  },

  navBackmeal: function(e) {
    this.setData({
      setitemdialoag: false
    })
  },

  // 商品推荐
  swiperImg: function(res) {
    var that = this;
    wx.request({
      url: util.api + 'detail/gooditem.json',
      method: 'GET',
      header: {
        'Content-type': 'application/json'
      },
      success: function(res) {
        that.setData({
          slider: res.data.result
        })
      },
      fail: function(res) {

      }
    })
  },


  //返回顶部
  goScrolltop: function(e) {
    var that = this;
    that.setData({
      toView: 'index0'
    })

  },

  //页面加载时购物车数量
  countCart: function (e) {
    var that = this;
    wx.request({
      url: util.api + api.GetShopcart,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.data.MESSAGE.MESSAGE_CODE == 1) {
          var arr = res.data.RESULT || [];
          var counts = 0;
          //遍历购物车对其进行求和
          for (var i = 0; i < arr.length; i++) {
            counts = parseInt(counts) + parseInt(arr[i].Num);
          }
          let navCont = that.data.navCont;
          console.log(arr)
          //购物车商品数量
          that.setData({
            navCont: counts
          })
        }

      },
      fail: function (res) {}
    })
  },

  //加入购物车实时数量
  cartNumber: function() {
    var that = this;
    var arr = wx.getStorageSync('shopCart') || [];
    var counts = parseInt(that.data.num);
    //遍历购物车缓存对其进行求和
    for (var i = 0; i < arr.length; i++) {
      counts = counts + parseInt(arr[i].count);
    }
    let navCont = this.data.navCont;
    //购物车商品数量
    that.setData({
      navCont: counts
    })
  },

  // 加入购物车
  addCart: function(e) {
    var that = this;
    var itemcart = that.data.itemcart;
    var id = e.currentTarget.dataset.id;
    var num = that.data.num;
    var arr = wx.getStorageSync('shopCart') || [];
    if (isNaN(num)) {
      $Toast({
        content: '非法的字符!',
        icon: 'prompt_fill',
        duration: 1
      });

      this.setData({
        num: 1,
        minusStatus: true
      })

    } else {

      that.cartNumber();
      $Toast({
        content: "加入购物车成功!",
        icon: 'success',
        duration: 1
      });

      for (var i = 0; i < itemcart.length; i++) {
        if (itemcart[i].id == id) {
          itemcart[i].count = num;
          itemcart[i].checked = true;
          if (arr.length > 0) {
            for (var j in arr) {
              if (arr[j].id == id) {
                arr[j].count = arr[j].count + num;
                try {
                  wx.setStorageSync('shopCart', arr)
                } catch (e) {
                  console.log(e)
                }
                return;
              }
            }
            arr.push(itemcart[i]);
          } else {
            arr.push(itemcart[i]);
          }

          try {
            wx.setStorageSync('shopCart', arr)
            return;
          } catch (e) {
            console.log(e)
          }
        }
      }

    }

  },


  // 加入收藏
  collectionTap: function(e) {
    var that = this;
    var itemcart = that.data.itemcart;
    var id = e.currentTarget.dataset.id;
    var num = that.data.num;
    var arr = wx.getStorageSync('shopCollect') || [];
    $Toast({
      content: "收藏成功!",
      icon: 'success',
      duration: 1
    });
    that.setData({
      icon_collect: false
    })
    for (var i = 0; i < itemcart.length; i++) {
      if (itemcart[i].id == id) {
        itemcart[i].count = 1;
        if (arr.length > 0) {
          for (var j in arr) {
            if (arr[j].id == id) {
              $Toast({
                content: '此商品已收藏!',
                icon: 'prompt_fill',
                duration: 1
              });

              try {
                wx.setStorageSync('shopCollect', arr)
              } catch (e) {
                console.log(e)
              }
              return;
            }
          }
          arr.push(itemcart[i]);
        } else {
          arr.push(itemcart[i]);
        }
        try {
          wx.setStorageSync('shopCollect', arr)
          return;
        } catch (e) {
          console.log(e)
        }
      }
    }
  },

  gotoDetail: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    util.navigateTo('../productdetail/productdetail?id=' + id)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var arr = wx.getStorageSync('history') || [];
    that.setData({
      hisid: options.id
    })
    wx.getSystemInfo({
      success: res => this.setData({
        cHeight: res.windowHeight
      })
    })
    var dataval = [];
    for (var i = 0; i < this.data.dataitem.length; i++) {
      dataval.push(this.data.dataitem[i].id)
    }

    let itemArr = dataval.map(function(v, i) {
      return v * 500
    })
    this.setData({
      itemArr
    })
    wx.showLoading({
      title: '加载中...',
    })
    var that = this;
    wx.request({
      url: util.api + api.GetProductDetail,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          ProductID: options.id,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.data.RESULT.ProductID == options.id) {
          that.setData({
            Bewrite: res.data.RESULT.Bewrite,
            CuCun: res.data.RESULT.CuCun,
            Integral: res.data.RESULT.Integral,
            IsShowOutofstock: res.data.RESULT.IsShowOutofstock,
            MemCardSignType: res.data.RESULT.MemCardSignType,
            OriginalPrice: res.data.RESULT.OriginalPrice,
            ProductBrand: res.data.RESULT.ProductBrand,
            ProductCataID: res.data.RESULT.ProductCataID,
            ProductCode: res.data.RESULT.ProductCode,
            ProductID: res.data.RESULT.ProductID,
            ProductItemID: res.data.RESULT.ProductItemID,
            ProductName: res.data.RESULT.ProductName,
            ProductWeight: res.data.RESULT.ProductWeight,
            PromotionTitle: res.data.RESULT.PromotionTitle,
            Remark: res.data.RESULT.Remark,
            ShowOutofstockPcStr: res.data.RESULT.ShowOutofstockPcStr,
            StockNum: res.data.RESULT.StockNum,
            cataname: res.data.RESULT.cataname,
            comment6: res.data.RESULT.comment6,
            isComb: res.data.RESULT.isComb,
            iscomb: res.data.RESULT.iscomb,
            isshoucang: res.data.RESULT.isshoucang,
            issince: res.data.RESULT.issince
          })
          console.log(res.data.RESULT)
          console.log(res.data.RESULT.ProductID)
          if (res.data.RESULT.Bewrite == '' || res.data.RESULT.Bewrite == null || res.data.RESULT.Bewrite == undefined){
            wxParser.parse({
              bind: 'detail', //绑定的数据名称
              html: '<b>暂无图文详情</b>', //HTML 内容
              target: that, //绑定数据的模块对象
              enablePreviewImage: true, //是否启用富文本内的图片预览功能
              tapLink: (url) => { //点击超链接时的回调函数
              }
            });
          } else {
            wxParser.parse({
              bind: 'detail', //绑定的数据名称
              html: res.data.RESULT.Bewrite, //HTML 内容
              target: that, //绑定数据的模块对象
              enablePreviewImage: true, //是否启用富文本内的图片预览功能
              tapLink: (url) => { //点击超链接时的回调函数
              }
            });
          }
          
        }
        wx.hideLoading()
      },
      fail: function (res) {
        that.setData({
          showSkeleton: false
        })
        wx.hideLoading()
      }

    })
    /*
    wx.request({
      url: util.api + 'detail/item.json',
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        var itemdetail = [];
        var itemtxt = [];
        var itemsrc = [];
        for (var i = 0; i < res.data.result.length; i++) {
          if (res.data.result[i].id == options.id) {
            itemdetail.push(res.data.result[i].imgItem)
            itemtxt.push(res.data.result[i])
            that.setData({
              cartitem: res.data.result[i]
            })
          }

          // 模拟套餐数据
          if (res.data.result[i].id == "496553" || res.data.result[i].id == "496551" || res.data.result[i].id == "496552" || res.data.result[i].id == "496554") {
            that.setData({
              setmealstatus: true
            })
          }else{
            that.setData({
              setmealstatus: false
            })
          }
          
        }

        for (var i = 0; i < itemdetail[0].length; i++) {
          var item = itemdetail[0][i]
          itemsrc.push(item.imgSrc)
        }

        that.setData({
          itemdetail: itemsrc,
          itemtxt: itemtxt
        })

        if (itemtxt[0].goodpic == '' || itemtxt[0].goodpic == null || itemtxt[0].goodpic == undefined) {
          wxParser.parse({
            bind: 'detail', //绑定的数据名称
            html: '<b>暂无图文详情</b>', //HTML 内容
            target: that, //绑定数据的模块对象
            enablePreviewImage: true, //是否启用富文本内的图片预览功能
            tapLink: (url) => { //点击超链接时的回调函数
            }
          });
        } else {
          wxParser.parse({
            bind: 'detail', //绑定的数据名称
            html: itemtxt[0].goodpic, //HTML 内容
            target: that, //绑定数据的模块对象
            enablePreviewImage: true, //是否启用富文本内的图片预览功能
            tapLink: (url) => { //点击超链接时的回调函数
            }
          });
        }

        that.swiperImg()
        that.setmeal()
        that.slideimg()
        wx.hideLoading()
      },
      fail: function(res) {
        wx.hideLoading()
      }
    })*/
/*
    wx.request({
      url: util.api + 'goodsList/list.json',
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        var itemcart = [];
        for (var i = 0; i < res.data.result.length; i++) {
          for (var j = 0; j < res.data.result[i].list.length; j++) {
            if (res.data.result[i].list[j].id == options.id) {
              itemcart.push(res.data.result[i].list[j])
            }
          }
        }

        // 浏览记录
        for (var i = 0; i < itemcart.length; i++) {
          if (itemcart[i].id == options.id) {
            itemcart[i].count = 1;
            itemcart[i].checked = true;
            if (arr.length > 0) {
              for (var j in arr) {
                if (arr[j].id == options.id) {
                  try {
                    wx.setStorageSync('history', arr)
                  } catch (e) {
                    console.log(e)
                  }
                  return;
                }
              }
              arr.push(itemcart[i]);
            } else {
              arr.push(itemcart[i]);
            }
            try {
              wx.setStorageSync('history', arr)
              return;
            } catch (e) {
              console.log(e)
            }
          }
        }

        that.setData({
          itemcart: itemcart
        })
        wx.hideLoading()
      },
      fail: function(res) {
        wx.hideLoading()
      }
    })
*/

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var arr = wx.getStorageSync('history') || [];
    this.countCart()
    this.setData({
      sliders: arr
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    //获取屏幕尺寸
    const screenWidth = wx.getSystemInfoSync().windowWidth;
    const screenHeight = wx.getSystemInfoSync().windowHeight;
    this.setData({
      listIndex: screenHeight / (screenWidth * 0.4),
      screenWidth: screenWidth,
      screenHeight: screenHeight
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  }


})